import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import { renderValveOpen,renderSignalIntensity } from '@/utils/utils';

import debounce from 'lodash/debounce';
import BuildModalTitle from '@/components/BuildModalTitle';
import ConcentratorConfig from './ConcentratorConfig';
import ReactDataGrid from 'react-data-grid';
import AddMechanical from './AddMechanical'
import request from '@/utils/request';
import Detail from "./Detail";
import Logs from './Logs'
import AreaMap from "@/components/AreaMap";
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ concentrators, loading, global }) => ({
  concentrators,
  global,
  loading: loading.models.concentrators,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      concentrators: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        concentrators: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'concentrators/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'concentrators/changeLoaded',
          });
          dispatch({
            type: 'concentrators/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    if(e.target){
      dispatch({
        type: 'concentrators/changeScroll',
        payload: {
          x: e.target.scrollLeft,
          y: e.target.scrollTop,
        },
      });
    }

  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'concentrators/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'concentrators/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          concentrators: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };
  renderSimpleForm() {
    const {
      concentrators: { searchParams },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label="采集器号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="IMEI">
          {getFieldDecorator('imei', {
            initialValue: searchParams.imei,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
    {/*    <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        concentrators: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }
  handleAddMechanical=()=>{
    const formValues = this.configMechanicalFormRef.props.form.getFieldsValue();
    const state = this.configMechanicalFormRef.state;
    const editRecord=this.state.editRecord
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    console.log('meterskey',meterskey)

    const metersArr={}
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`meter_number-${meterskey[i]}`]){
        if(formValues[`meter_number-${meterskey[i]}`].length===10||formValues[`meter_number-${meterskey[i]}`].length===12){
          metersArr[`port${meterskey[i]}`]={
            meter_number:formValues[`meter_number-${meterskey[i]}`],
            initial_value:Number(formValues[`initial_value-${meterskey[i]}`]),
            dial_value:Number(formValues[`dial_value-${meterskey[i]}`]),
            caliber:formValues[`caliber-${meterskey[i]}`],
            remark:formValues[`remark-${meterskey[i]}`],
            meter_images:state[`port${meterskey[i]}PicArr`]
          }
        }else{
          message.error(`端口${meterskey[i]}水表号必须长度为10/12位`)
          return
        }

      }

    }
    console.log('metersArr',metersArr);
    let sendData={
      latitude:editRecord.latitude,
      longitude:editRecord.longitude,
      address:formValues.address,
      concentrator_images: state.concentratorPicArr,
      remark: formValues.remark,
      type:2,
      "config": {
        ...editRecord.config,
        "meter_config": metersArr
      }
    }
    console.log('sendData',sendData)
    const that=this;
    // return
    this.props.dispatch({
      type: 'concentrators/edit',
      payload: {
       ...sendData,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改集中器配置成功');
        that.setState({
          configConcentratorsModal: false,
        });
        const {
          concentrators: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  }
  handleAdd = () => {
    const formValues = this.addConcentratorsForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'concentrators/add',
      payload: {
        ...formValues,
        // config:{
        //   platform:formValues.platform
        // }
      },
      callback() {
        message.success('添加采集器成功');
        that.setState({
          addConcentratorsModal: false,
        });
        const {
          concentrators: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      meter_number:'',
      number:'',
      imei:'',
      page: 1,
      per_page: 50,
    });
  };

  handleEdit = () => {
    const formValues = this.editMechanicalFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `concentrators/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改采集器成功');
        that.setState({
          editConcentratorsModal: false,
        });
        const {
          concentrators: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `concentrators/remove`,
      payload: { id },
      callback: () => {
        message.success('删除采集器成功');
        const {
          concentrators: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleImport=()=>{
    const formValues =this.importFormRef.props.form.getFieldsValue();
    const that=this;
    console.log('formValues',formValues)
    if(!formValues.file||formValues.file.fileList.length===0){
      message.error('请选择文件');
      return false
    }

    var formData = new FormData();
    formData.append("file", formValues.file.file);
    formData.append("protocol_id", formValues.protocol_id);
    formData.append("start_row", formValues.start_row);
    formData.append("end_row", formValues.end_row);
    request(`/meter_files`, {
      method: 'POST',
      data: formData
    }).then((response)=> {
      console.log(response);
      if(response.status===200){
        message.success('批量导入采集器成功')
        const {
          concentrators: { searchParams },
        } = that.props;
        that.setState({
          importModal:false
        })
        that.handleSearch(searchParams);

      }
    })
  }

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={false}/>;
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={true}/>;
        break;
      case 2:
        type = 'close-circle', color = '#fe5810', text = '未上报';
        break;
      case 3:
        type = 'close-circle', color = '#fe1b2e', text = '异常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      concentrators: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username');
    const columns = [
      {
        name: '序号',
        width: 50,
        frozen: true,
        key: '_index',
        formatter: (event) => {
          const {
            concentrators: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '采集器号',
        width: 120,
        frozen: true,
        key: 'number',
        formatter: (event) => {
          return <span style={{color:'#037aff',cursor:'pointer'}} onClick={()=>{
            this.setState({
              editRecord: event.row,
              infoModal: true,
            });
          }}>{event.value}</span>
        },

      },
      {
        name: '水表个数',
        key: 'imei2',
        frozen: true,
        width: 80,
        formatter: (event) => {
          return event.row.config.meter_config?Object.keys(event.row.config.meter_config).length:''
        },
      },
      {
        name: '采集时间',
        width: 170,
        key: 'upload_time',
        formatter: (event) => {
          return (event.row.concentrator_info&&event.row.concentrator_info.upload_time)?event.row.concentrator_info.upload_time:''
          // return ''
        },

      },
      {
        name: '平台',
        key: 'platform',
        width: 80,
        formatter: (event) => {
          return event.row.config.platform?event.row.config.platform:''
          // return ''
        },
      },
      {
        name: 'IMEI',
        key: 'imei',
        width: 160,
      },
      {
        name: '版本号',
        key: 'version',
        width: 80,
        formatter: (event) => {
          return (event.row.concentrator_info&&event.row.concentrator_info.main_software_version)?`${event.row.concentrator_info.main_software_version}.${event.row.concentrator_info.sub_software_version}`:''
          // return ''
        },
      },
      {
        name: '创建时间',
        key: 'created_at',
        width: 170,
      },
      {
        name: '地址',
        key: 'address',
        width: 170,
      },
      {
        name: '备注',
        key: 'remark',
        width: 100,
      },
      {
        name: '操作',
        width: 430,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            find(this.permissions, { name: 'concentrator_operation' }) &&
            <Fragment>
              <Button
                icon="setting"
                type="primary"
                size="small"
                onClick={
                  () => {

                    this.setState({
                      configConcentratorsModal: true,
                      editRecord: event.row,
                    });
                  }
                }
              >
                编辑/配置
              </Button>
              <Button
                icon="file-text"
                type="primary"
                size="small"
                onClick={
                  () => {

                    this.setState({
                      logModal: true,
                      editRecord: event.row,
                    });
                  }
                }
              >
                操作记录
              </Button>
              {
                 find(this.permissions, { name: 'concentrator_delete' }) &&
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    confirm({
                      title: `确定要删除采集器"${event.row.number}"吗?`,
                      content: '删除后数据不可逆，请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered:true,
                      maskClosable: true,
                      onOk() {
                        that.handleDelete(event.row.id);
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });

                  }
                  }
                >删除
                </Button>
              }

            </Fragment>
          }


        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>采集器管理</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>采集器总数量(个)</p>
            <h4>{meta.total}</h4>
          </div>
            <div size="large" className="table-info-right-item">
              {
                find(this.permissions, {name: 'concentrator_operation'}) && <Button
                  icon="plus"
                  style={{marginLeft: 8}}
                  type="primary"
                  onClick={
                    () => {
                      this.setState({
                        addConcentratorsModal: true,
                      });
                    }
                  }
                >
                  添加采集器
                </Button>
              }
            </div>


        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (index,row) => {
                if (!row) {
                  return;
                }
                this.props.dispatch({
                  type: 'concentrators/changeSelectRow',
                  payload:[index],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          concentrators: {  scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop =0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addConcentratorsModal} modalClass="addConcentratorsModal" title="添加集中器"/>}
        visible={this.state.addConcentratorsModal}
        centered
        onOk={()=>{
          that.handleAdd()
        }}
        className="addConcentratorsModal"
        onCancel={() => {
          this.setState({ addConcentratorsModal: false });
        }}

      >
        <AddMechanical  wrappedComponentRef={(inst) => this.addConcentratorsForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editConcentratorsModal} modalClass="editConcentratorsModal" title="修改集中器"/>}
        visible={this.state.editConcentratorsModal}
        centered
        destroyOnClose
        onOk={()=>{
          that.handleEdit()
        }}
        className="editConcentratorsModal"
        onCancel={() => {
          this.setState({ editConcentratorsModal: false });
        }}

      >
        <AddMechanical editRecord={this.state.editRecord}  wrappedComponentRef={(inst) => this.editMechanicalFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.configConcentratorsModal} modalClass="configConcentratorsModal" title={"配置集中器"+this.state.editRecord.number}/>}
        visible={this.state.configConcentratorsModal}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={()=>{
          that.handleAddMechanical()
        }}
        width={1100}
        className="configConcentratorsModal"
        onCancel={() => {
          this.setState({ configConcentratorsModal: false });
        }}

      >
        <ConcentratorConfig type={'config'} editRecord={this.state.editRecord}  wrappedComponentRef={(inst) => this.configMechanicalFormRef = inst}/>
      </Modal>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={850}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.logModal} modalClass="logModal" title={this.state.editRecord.number+"操作记录"}/>}
        visible={this.state.logModal}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={()=>{
          that.handleAddMechanical()
        }}
        width={'100vw'}
        style={{paddingBottom:'0'}}
        className="logModal"
        onCancel={() => {
          this.setState({ logModal: false });
        }}
        footer={null}
      >
        <Logs type={'config'} editRecord={this.state.editRecord} id={this.state.editRecord.id}  wrappedComponentRef={(inst) => this.configMechanicalFormRef = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
